//
//  OrderFillVC.m
//  Ufan
//
//  Created by yangqingluo on 15/12/7.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "OrderFillVC.h"
#import "OrderNameCell.h"
#import "OrderAddressCell.h"
#import "AddressManageVC.h"
#import "AddressEditVC.h"
#import "OrderQuantityCell.h"
#import "LeftOrderPayVC.h"

@interface OrderFillVC ()<UITableViewDataSource,UITableViewDelegate>


@property (nonatomic, strong) UFShoppingProduct *product;
@property (nonatomic, strong) UFItem *item;
@property (nonatomic, strong) UITableView *showTableView;

@property (nonatomic, strong) UIView *bottomBar;
@property (nonatomic, strong) UILabel *bottomPriceLabel;
@end

@implementation OrderFillVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.showTableView reloadData];
}

- (instancetype)initWithItem:(UFItem *)item{
    self = [super init];
    
    if (self) {
        self.item = item;
        self.product = [UFShoppingProduct new];
        self.product.productItemId = [self.item.idString copy];
        self.product.quantity = 1;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(245, 245, 245, 1.0);
    [self setupBarButtonItem];
    
    [self.view addSubview:self.bottomBar];

    [self getDefaultAddress];
}

- (void)setupBarButtonItem{
    self.title = @"填写订单";
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 64, 44)];
    [backButton setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 0, 12, 48)];
    backButton.tag = 988;
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];
}
#pragma response
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:UF_Router_Event_ProductQuantity]) {
        self.bottomPriceLabel.text = [NSString stringWithFormat:@"合计：%.2f 元",self.item.retailPrice * self.product.quantity];
    }
}

-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)pushOrder{
    if ([AppPublic shareInstanceApp].addressSelected) {
        
        [self showHudInView:self.view hint:nil];
        [QKHttpManager checkOrdersWithAddress:[AppPublic shareInstanceApp].addressSelected.idString product:self.product invoice:nil completion:^(NSObject *object, NSError *error){
            [self hideHud];
            if ([object isKindOfClass:[NSDictionary class]]) {
                NSDictionary *respDic = (NSDictionary *)object;
                if ([respDic[@"code"] intValue] == QKHTTP_SUCCESS) {

                    NSString *partner = @"2088121526915815";
                    NSString *seller = @"samveslie@163.com";
                    
                    /*
                     *生成订单信息及签名
                     */
                    //将商品信息赋予AlixPayOrder的成员变量
                    Order *order = [[Order alloc] init];
                    order.partner = partner;
                    order.seller = seller;
                    order.tradeNO = respDic[@"paymentId"];
                    order.productName = self.productInfo.name;
                    
                    order.amount = respDic[@"totalPrice"]; //商品价格

                    
                    order.itemPrice = self.item.retailPrice;
                    order.quantity = (int)self.product.quantity;
                    
                    UFOrderInfo *orderInfo = [UFOrderInfo new];
                    orderInfo.totalPrice = [respDic[@"totalPrice"] doubleValue];
                    
                    LeftOrderPayVC *payVC = [[LeftOrderPayVC alloc]initWithOrder:orderInfo];
                    payVC.payInfo = order;
                    
                    
                    [self.navigationController pushViewController:payVC animated:YES];
                    
                }
            }
            
            [self showHint:httpRespString(error, object)];
        }];
    }
    else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择收货地址" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
    }
}

- (void)getDefaultAddress{
    [QKHttpManager getDefaultAddressCompletion:^(NSObject *object, NSError *error){
        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *respDic = (NSDictionary *)object;
            if ([respDic[@"code"] intValue] == QKHTTP_SUCCESS) {
                [AppPublic shareInstanceApp].addressSelected = addressFromDic(respDic[@"address"]);
                [self.showTableView reloadData];
            }
        }
    }];
}

#pragma getter
- (UITableView *)showTableView{
    if (!_showTableView) {
        _showTableView= [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStylePlain];
        _showTableView.multipleTouchEnabled = YES;
        _showTableView.dataSource = self;
        _showTableView.delegate = self;
        _showTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_showTableView setBackgroundColor:[UIColor clearColor]];
        
        [self.view insertSubview:_showTableView belowSubview:self.bottomBar];
    }
    
    return _showTableView;
}

- (UIView *)bottomBar{
    if (!_bottomBar) {
        _bottomBar = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height - TAB_BAR_HEIGHT - STATUS_BAR_HEIGHT, self.view.width, TAB_BAR_HEIGHT)];
        _bottomBar.backgroundColor = [UIColor whiteColor];
        _bottomBar.layer.shadowColor = [UIColor blackColor].CGColor;
        _bottomBar.layer.shadowOffset = CGSizeMake(0, -1);
        _bottomBar.layer.shadowOpacity = 0.2;
        
        UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        buyButton.frame = CGRectMake(0, 0, 100, 36);
        buyButton.center = CGPointMake(_bottomBar.width - 0.5 * buyButton.width - 10, 0.5 * _bottomBar.height);
        buyButton.titleLabel.font = [UIFont systemFontOfSize:16.0];
        [buyButton setBackgroundColor:[UIColor orangeColor]];
        buyButton.layer.cornerRadius = 5;
        buyButton.layer.masksToBounds = YES;
        [buyButton setTitle:@"提交订单" forState:UIControlStateNormal];
        [buyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buyButton addTarget:self action:@selector(pushOrder) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBar addSubview:buyButton];
        
        self.bottomPriceLabel.center = CGPointMake(buyButton.left - 0.5 * self.bottomPriceLabel.width - 10, 0.5 * _bottomBar.height);
        [_bottomBar addSubview:self.bottomPriceLabel];
    }
    
    return _bottomBar;
}

- (UILabel *)bottomPriceLabel{
    if (!_bottomPriceLabel) {
        _bottomPriceLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
        _bottomPriceLabel.textColor = [UIColor orangeColor];
        _bottomPriceLabel.font = [UIFont systemFontOfSize:14.0];
        _bottomPriceLabel.textAlignment = NSTextAlignmentRight;
        _bottomPriceLabel.text = [NSString stringWithFormat:@"合计：%.2f 元",self.item.retailPrice * self.product.quantity];
    }
    
    return _bottomPriceLabel;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        NSString *CellIdentifier = @"OrderNameCell";
        OrderNameCell *cell = (OrderNameCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[OrderNameCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.name = self.productInfo ? self.productInfo.name : self.item.name;
        
        
        return cell;
    }
    else if (indexPath.row == 5){
        NSString *CellIdentifier = @"OrderAddressCell";
        OrderAddressCell *cell = (OrderAddressCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[OrderAddressCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
        return cell;
    }
    else if (indexPath.row == 2){
        NSString *CellIdentifier = @"OrderQuantityCell";
        OrderQuantityCell *cell = (OrderQuantityCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[OrderQuantityCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.inventory = self.item.inventory;
        cell.product = self.product;
        [cell reloadButtonState];
        
        return cell;
    }
    else{
        NSString *itemCellIdentifier = @"itemCellIdentifier";
        
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:itemCellIdentifier];
        
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:itemCellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.font = [UIFont systemFontOfSize:14.0];
            
            cell.detailTextLabel.font = cell.textLabel.font;
            cell.detailTextLabel.textColor = cell.textLabel.textColor;
            
            
            UIView *bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(15, cell.height - 0.5, tableView.width - 30, 0.5)];
            bottomLineView.backgroundColor = UFCOLOR_GRAYLINE;
            [cell.contentView addSubview:bottomLineView];
        }
        
        switch (indexPath.row) {
            case 1:{
                cell.textLabel.text = @"单价";
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f 元",self.item.retailPrice];
            }
                break;
                
                
            case 3:{
                cell.textLabel.text = @"邮费";
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",@"包邮"];
            }
                break;
                
            case 4:{
                cell.textLabel.text = @"手机号";
                cell.detailTextLabel.text = starMiddle([AppPublic shareInstanceApp].username_password.username);
            }
                break;
                
                
            default:
                break;
        }
        
        return cell;
    }
    
    
    return [UITableViewCell new];
}


#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return [OrderNameCell tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    else if (indexPath.row == 5){
        return [OrderAddressCell tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    else if (indexPath.row == 2){
        return [OrderQuantityCell tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    
    return 44;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 5) {
        if ([AppPublic shareInstanceApp].addressSelected) {
            AddressManageVC *amVC = [AddressManageVC new];
            [self.navigationController pushViewController:amVC animated:YES];
        }
        else{
            AddressEditVC *aeVC = [[AddressEditVC alloc]initWithAddress:nil];
            [self.navigationController pushViewController:aeVC animated:YES];
        }
    }
}

@end
